const WXAPI = require('apifm-wxapi')
const util = require('./util')
/**
 * type: order 支付订单 recharge 充值 paybill 优惠买单
 * data: 扩展数据对象，用于保存参数
 */
function wxpay(type, money, orderId, redirectUrl, data) {
const postData = {
    token: wx.getStorageSync('token'),
    money: money,
    remark: "在线充值",
  }
  if (type === 'order') {
    postData.remark = "支付订单 ：" + orderId;
    postData.nextAction = {
      type: 0,
      id: orderId
    };
  }
  if (type === 'paybill') {
    postData.remark = "优惠买单 ：" + data.money;
    postData.nextAction = {
      type: 4,
      uid: wx.getStorageSync('uid'),
      money: data.money
    };
  }
  postData.payName = postData.remark;
  postData.orderId = orderId
  if (postData.nextAction) {
    postData.nextAction = JSON.stringify(postData.nextAction);  
  }

  WXAPI.wxpay(postData).then(function (res) {

    if (res.code == 0) {
      // 发起支付
      wx.requestPayment({
        timeStamp: res.data.timeStamp,
        nonceStr: res.data.nonceStr,
        package: res.data.package,
        signType: res.data.signType,
        paySign: res.data.paySign,
        fail: function (err) {
           WXAPI.payClose(orderId)
          wx.showToast({
            title: '支付失败:' 
          })
          if (redirectUrl) {
            wx.redirectTo({
              url: redirectUrl,
            })
          }
        },
        success: function () {
          // 提示支付成功
          wx.showToast({
            title: '支付成功'
          })
          if (redirectUrl) {
            wx.redirectTo({
              url: redirectUrl,
            })
          }
        }
      })
    } else {
      wx.showModal({
        title: '出错了',
        content: res.msg,
        showCancel: false
      })      
    }
  })
}

async function toPayTap(dataset) {


  const orderId = dataset.id;
  let money = dataset.money;
  const needScore = dataset.score;
  const res = await WXAPI.userAmount(wx.getStorageSync('token'));
 
  if (res.code === 0) {
    // 增加提示框
    if (res.data.score < needScore) {
      wx.showToast({
        title: '您的积分不足，无法支付',
        icon: 'none'
      })
      return;
    }
    let _msg = '订单金额: ' + money +' 元'
    if (res.data.balance > 0) {
      _msg += ',可用余额为 ' + res.data.balance +' 元'
      if (money - res.data.balance > 0) {
        _msg += ',仍需微信支付 ' + util.sub(money , res.data.balance)  + ' 元'
      }
    }
    if (needScore > 0) {
      _msg += ',并扣除 ' + needScore + ' 积分'
    }
    money = money - res.data.balance
   await  wx.showModal({
      title: '请确认支付',
      content: _msg,
      confirmText: "确认支付",
      cancelText: "取消支付",
      success: async function (res) {

        if (res.confirm) {
         await _toPayTap(orderId, money)
        } else {
          console.log('用户点击取消支付')
          wx.redirectTo({
            url: '/pages/all-orders/index',
          })
        }
      
      }
    });
  } else {
    wx.showModal({
      title: '错误',
      content: '无法获取用户资金信息',
      showCancel: false
    })
  }
  return true;
}
async function _toPayTap(orderId, money){
  if (money <= 0) {
    // 直接使用余额支付
  const res = await  WXAPI.orderPay(wx.getStorageSync('token'), orderId)

    if(res.code !== 0){
      wx.showModal({
        content: res.msg,
        showCancel: false
      })
      return 
    }
    wx.redirectTo({
      url: '/pages/all-orders/index',
    })

  } else {
    wxpay('order', money, orderId, "/pages/all-orders/index");
  }
}


module.exports = {
  wxpay: wxpay,
  toPayTap:toPayTap
}